package com.qilin.hscs.hm.mqtt.config;

import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by 10188 on 2018/3/20.
 */
@Configuration
public class MqttConfig {


    @Value("${mqtt.connect.userName}")
    private String username;

    @Value("${mqtt.connect.passWord}")
    private String password;


    @Value("${mqtt.innerHost}")
    private String innerHost;

    @Value("${mqtt.outterHost}")
    private String outterHost;

    @Value("${mqtt.message.qos}")
    private int qos;

    @Value("${mqtt.options.connectionTimeout}")
    private int connectionTimeout;

    @Value("${mqtt.options.keepAliveInterval}")
    private int keepAliveInterval;

    @Value("${mqtt.message.retained}")
    private boolean retained;

    @Bean
    public MqttConnectOptions getConnectionOptions () {
        // new mqttConnection 用来设置一些连接的属性
        MqttConnectOptions options = new MqttConnectOptions();
        // 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
        // 换而言之，设置为false时可以客户端可以接受离线消息
        options.setCleanSession(true);
        // 设置连接的用户名和密码
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        // 设置超时时间
        options.setConnectionTimeout(connectionTimeout);
        // 设置会话心跳时间
        options.setKeepAliveInterval(keepAliveInterval);
        return options;
    }

    @Bean(name = "innerHost")
    public String getInnerHost() {
        return innerHost;
    }

    @Bean(name = "outterHost")
    public String getOutterHost() {
        return outterHost;
    }
    @Bean
    public MqttMessage getMqttMessage() {
        MqttMessage message = new MqttMessage();
        //设置服务质量
        message.setQos(qos);
        //设置是否在服务器中保存消息体
        message.setRetained(true);
        return message;
    }

}
